package com.dhz.common.solr.server;

import org.apache.solr.client.solrj.SolrClient;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Solr服务中存在多core时的client工厂类
 *
 * @author Fyduan
 */
public class MulticoreSolrClientFactory extends SolrClientFactoryBase {
    /** Map容器：每个Core对应的client实例 */
    private Map<String, SolrClient> clientMap = new LinkedHashMap<String, SolrClient>();

    protected MulticoreSolrClientFactory() {
        super();
    }

    public MulticoreSolrClientFactory(SolrClient solrClient) {
        this(solrClient, Collections.emptyList());
    }

    public MulticoreSolrClientFactory(SolrClient solrClient, String... cores) {
        this(solrClient, (cores == null ? Collections.emptyList() : Arrays.asList(cores)));
    }

    public MulticoreSolrClientFactory(SolrClient solrClient, List<String> cores) {
        super(solrClient);
        for (String core : cores) {
            addSolrClientForCore(createSolrClientForCore(solrClient, core), core);
        }
    }

    /**
     * 添加core对应的SolrClient到{@link MulticoreSolrClientFactory#clientMap}，覆盖相同
     * @param solrClient {@link SolrClient} client实例
     * @param core coreName
     */
    public void addSolrClientForCore(SolrClient solrClient, String core) {
        clientMap.put(core, solrClient);
    }

    /**
     * 删除core对应的solrClient，From {@link MulticoreSolrClientFactory#clientMap}
     * @param core coreName
     */
    public void removeSolrClient(String core) {
        if (clientMap.containsKey(core)) {
            clientMap.remove(core);
        }
    }

    @Override
    public SolrClient getSolrClient(String coreName) {
        if (!StringUtils.hasText(coreName)) {
            return getSolrClient();
        }

        if (!clientMap.containsKey(coreName)) {
            clientMap.put(coreName, createSolrClientForCore(getSolrClient(), coreName));
        }
        return clientMap.get(coreName);
    }

    @Override
    public List<String> getCores() {
        return new ArrayList<String>(clientMap.keySet());
    }

    @Override
    public void destroy() throws Exception {
        super.destroy();
        for (SolrClient client : clientMap.values()) {
            destroy((client));
        }
    }

    private SolrClient createSolrClientForCore(SolrClient clientReference, String core) {
        if (StringUtils.hasText(core)) {
            return SolrClientUtils.clone(clientReference, core);
        }
        return clientReference;
    }
}
